package cn.com.utils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class NearestHour {

    /**
     * 四舍五入到最近小时
     *
     * @param dateTime 日期时间
     *
     * @return {@link LocalDateTime }
     */
    public static LocalDateTime roundToNearestHour(LocalDateTime dateTime) {
        int minute = dateTime.getMinute();
        if (minute < 30) {
            // 舍入到上一个整点
            return dateTime.withMinute(0).withSecond(0).withNano(0);
        } else {
            // 舍入到下一个整点
            return dateTime.plusHours(1).withMinute(0).withSecond(0).withNano(0);
        }
    }

    public static void main(String[] args) {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime rounded = roundToNearestHour(now);

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        System.out.println("当前时间: " + now.format(formatter));
        System.out.println("取最近的整点时间: " + rounded.format(formatter));
    }
}
